package com.example.pei.ithinklearnt.db.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

import com.example.pei.ithinklearnt.Config;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.db.MyPrivateConversation;
import com.example.pei.ithinklearnt.db.OrderDBHelper;


import java.util.ArrayList;
import java.util.HashMap;

import cn.bmob.v3.BmobUser;


/**
 * 评论表
 * Created by Pei on 2018/4/15.
 */

public class PrivateConverDaoOrder {


    private static HashMap<String, PrivateConverDaoOrder> daoMap = new HashMap<>();


    private OrderDBHelper ordersDBHelper;

    // 列定义
    private final String[] ORDER_COLUMNS = new String[] {"id","status"};

    private PrivateConverDaoOrder(Context context, String uId) {


        String DBName = uId+"_iThinkLearnt.db";
        ordersDBHelper = new OrderDBHelper(context,DBName);
    }

    static public PrivateConverDaoOrder getInstance(Context context){
        UserInfo user = BmobUser.getCurrentUser( UserInfo.class);
        String loginId=user.getObjectId();
        if(TextUtils.isEmpty(loginId)){
            throw new RuntimeException("you must login.");
        }
        PrivateConverDaoOrder dao = daoMap.get(loginId);
        if (dao == null) {
            dao = new PrivateConverDaoOrder(context,loginId);
            daoMap.put(loginId, dao);
        }
        return dao;
    }

    /**
     * 新增一条数据
     */
    public boolean insertComment(MyPrivateConversation conversation){

        String id=conversation.getId();
        int status=conversation.getStatus();
        SQLiteDatabase db = null;

        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();

            ContentValues contentValues = new ContentValues();
            contentValues.put(ORDER_COLUMNS[0], id);
            contentValues.put(ORDER_COLUMNS[1], status);

            db.insertOrThrow(OrderDBHelper.TABLE_PRIVATECONVERSATION, null, contentValues);

            db.setTransactionSuccessful();
            return true;
        }catch (SQLiteConstraintException e){
            Log.e("privateConverDaoOrder", "", e);
        }catch (Exception e){
            Log.e("privateConverDaoOrder", "", e);
        }finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return false;
    }

    //查询id的这个会话的状态 删除 或 非删除
    public int getPrivateConverStatus(String id){
        int status=0;

        SQLiteDatabase db = null;
        Cursor cursor = null;
        ArrayList<MyPrivateConversation> commentsArrayList = new ArrayList<>();

        try {
            db = ordersDBHelper.getReadableDatabase();
            //查询表
            cursor = db.query(OrderDBHelper.TABLE_PRIVATECONVERSATION,null,
                    "id=?",
                    new String[]{id},
                    null,null,null);

            if (cursor.moveToFirst()) {
                status = cursor.getInt(1);
            }
        }
        catch (Exception e) {
             Log.e("privateConverDaoOrder", "", e);
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }

        return status;
    }

    //查询这个会话的所有消息记录(不管是否未读已读)
    public ArrayList<MyPrivateConversation> loadAllPrivateConversations(String id){
        SQLiteDatabase db = null;
        Cursor cursor = null;
        ArrayList<MyPrivateConversation> commentsArrayList = new ArrayList<>();

        try {
            db = ordersDBHelper.getReadableDatabase();
            //查询表所有数据
            cursor = db.query(OrderDBHelper.TABLE_PRIVATECONVERSATION,null,null,null,null,null,null);

            //遍历游标
            for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
                MyPrivateConversation conversation = new MyPrivateConversation();
                conversation.setId(cursor.getString(cursor. getColumnIndex(ORDER_COLUMNS[0])));
                conversation.setStatus(cursor.getInt(cursor.getColumnIndex(ORDER_COLUMNS[1])));
                commentsArrayList.add(conversation);
            }
        }
        catch (Exception e) {
             Log.e("privateConverDaoOrder", "", e);
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }

        return commentsArrayList;
    }

    //批量更新所有变成非删除状态  表示这个会话刷新会出现
    public void updateBatchStatusUnDeleted(String id){

        SQLiteDatabase db = null;
        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();

            ContentValues value = new ContentValues();
            value.put(ORDER_COLUMNS[1],Config.STATUS_VERIFY_NONE);

            db.update(OrderDBHelper.TABLE_PRIVATECONVERSATION, value, "id=?", new String[]{id});

            db.setTransactionSuccessful();
        }
        catch (SQLiteConstraintException e){
            Log.e("privateConverDaoOrder", "", e);
        }catch (Exception e){
            Log.e("privateConverDaoOrder", "", e);
        }finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }

    }

    //批量更新所有变成删除  表示这个会话不会再出现除非有新的消息
    public void updateBatchStatusDeleted(String id){

        SQLiteDatabase db = null;
        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();

            ContentValues value = new ContentValues();
            value.put(ORDER_COLUMNS[1],Config.STATUS_DELETED);

            db.update(OrderDBHelper.TABLE_PRIVATECONVERSATION, value, "id=?", new String[]{id});

            db.setTransactionSuccessful();
        }
        catch (SQLiteConstraintException e){
            Log.e("privateConverDaoOrder", "", e);
        }catch (Exception e){
            Log.e("privateConverDaoOrder", "", e);
        }finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
    }

    /**
     * 统计查询  查询是否有这个id的对话
     */
    public boolean hasConversation(String id){
        int count = 0;

        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = ordersDBHelper.getReadableDatabase();
            cursor = db.query(OrderDBHelper.TABLE_PRIVATECONVERSATION,
                    new String[]{"COUNT(*)"},
                    ORDER_COLUMNS[1]+"= ? ",
                    new String[] {id},
                    null, null, null);

            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        }
        catch (Exception e) {
             Log.e("privateConverDaoOrder", "", e);
        }
        finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }

        return count==1;
    }

}
